import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';
import 'package:excel/excel.dart';
import 'package:body_measurement/models/measuring_task.dart';

class TaskDataSource extends DataTableSource {
  List<MeasuringTask> _data = [];

  @override
  DataRow? getRow(int index) {
    if (index >= _data.length) {
      return null;
    }

    return DataRow.byIndex(
      index: index,
      cells: [
        DataCell(Text((index + 1).toString())),
        DataCell(
          InkWell(
            onTap: () {},
            child: Text(_data[index].name, style: const TextStyle(color: Colors.blue)),
          ),
        ),
        DataCell(
          Text(
            _data[index].orderStatus.toString(),
            style: const TextStyle(overflow: TextOverflow.ellipsis),
            textAlign: TextAlign.center,
          ),
        ),
        DataCell(
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: _buildOrderItems(_data[index]),
          ),
        ),
        // 量体师
        DataCell(
          Text(
            _data[index].measurers.join('、'),
            style: const TextStyle(overflow: TextOverflow.ellipsis),
            textAlign: TextAlign.center,
          ),
        ),
        // 量体部位
        const DataCell(Text('')),
        DataCell(Text(_data[index].userName)),
        DataCell(
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextButton(onPressed: () {}, child: const Text('导入')),
              TextButton(onPressed: exportExcelFile, child: const Text('导出')),
            ],
          ),
        ),
      ],
    );
  }

  @override
  int get rowCount => _data.length;

  @override
  bool get isRowCountApproximate => false;

  @override
  int get selectedRowCount => 0;

  List<Widget> _buildOrderItems(MeasuringTask task) =>
      task.orderItems.map((e) => Text('${e.category} * ${e.quantity}')).take(2).toList();

  void updateTaskData(List<MeasuringTask> data) {
    _data = data;
    notifyListeners();
  }

  void exportExcelFile() async {
    var externalStorageDirectory = await getExternalStorageDirectory();
    Directory('${externalStorageDirectory!.path}/test1122').create(recursive: true).then((dir) {
      var excel = Excel.createExcel();
      var sheet = excel['mySheet'];
      var cell = sheet.cell(CellIndex.indexByString('A1'));
      cell.value = const TextCellValue('hello, flutter');
      var fileBytes = excel.save();
      String filepath = join('${dir.path}/员工名单.xlsx');
      File(filepath)
        ..createSync(recursive: true)
        ..writeAsBytesSync(fileBytes!, flush: true);
    });
  }
}
